package com.xjk.sifasuo.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xjk.sifasuo.MainActivity;
import com.xjk.sifasuo.MyApplication;
import com.xjk.sifasuo.R;
import com.xjk.sifasuo.activity.BaseActivity;
import com.xjk.sifasuo.activity.LoginActivity;
import com.xjk.sifasuo.activity.MineMessageActivity;
import com.xjk.sifasuo.activity.ResetPasswordActivity;
import com.xjk.sifasuo.bean.CommonBean;
import com.xjk.sifasuo.model.BaseModel;
import com.xjk.sifasuo.model.CheckMessageModel;
import com.xjk.sifasuo.model.CheckVersionModel;
import com.xjk.sifasuo.model.PhotoUploadModel;
import com.xjk.sifasuo.utils.CircleImageView;
import com.xjk.sifasuo.utils.ClearCacheUtils;
import com.xjk.sifasuo.utils.CommonUtils;
import com.xjk.sifasuo.utils.ConstantsUtils;
import com.xjk.sifasuo.utils.DownLoadService;
import com.xjk.sifasuo.utils.ImageLoaderModel;
import com.xjk.sifasuo.utils.IntentUtils;
import com.xjk.sifasuo.utils.NewWorkUtils;
import com.xjk.sifasuo.utils.SharePreferenceUtils;
import com.xjk.sifasuo.utils.ToastUtils;
import com.xjk.sifasuo.utils.UrlDomainUtil;
import com.yuyh.library.imgsel.ImgSelActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.ref.WeakReference;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;


/**
 * Created by zhouzhuo on 2017/6/29.
 */

public class MineFragment extends BaseFragment {
    private CircleImageView iv_photo;
    private TextView tv_userName,tv_phoneNumber;
    private RelativeLayout rl_message,rl_update,rl_clear_cache,rl_reset_password;
    private Button btn_login_out;
    private MyHandler handler;

    private String appUrl;
    private Activity activity;
    private View view_message;

    public void checkMessage() {
        String id = (String) SharePreferenceUtils.get(getActivity(),"id","");
        CheckMessageModel model = new CheckMessageModel();
        model.setCallBackListener(new BaseModel.CallBackListener<CommonBean>() {
            @Override
            public void success(CommonBean bean) {
                if(bean.code == 1){
                    view_message.setVisibility(View.VISIBLE);
                }else {
                    view_message.setVisibility(View.INVISIBLE);
                }

            }

            @Override
            public void failed() {

            }
        });
        model.check(id);
    }

    private class MyHandler extends Handler{
        private WeakReference<MineFragment> weakReference;
        private MyHandler(MineFragment mineFragment){
            weakReference = new WeakReference<>(mineFragment);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(weakReference.get()!=null){
                switch (msg.what){
                    case 0:
                        String photo = (String) msg.obj;
                        photo = UrlDomainUtil.photoHeader+photo;
                        Log.d("zhouzhuo","photo url=="+photo);
                        SharePreferenceUtils.put(getContext(),"photo",photo);
                        ImageLoaderModel.instance().displayImage(photo,iv_photo);
                        break;
                    case 1:
                        String message = (String) msg.obj;
                        if(!TextUtils.isEmpty(message)){
                            ToastUtils.showShort(getActivity(),message);
                        }
                        break;
                }
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.fragment_mine, null);
        initView(view);
        handler = new MyHandler(this);
        activity = getActivity();
        initData();
        return view;
    }

    public void initData() {
        //第一次创建时候
            String name;
            String number;
            String photo;
            name = (String) SharePreferenceUtils.get(getActivity(),"name","");
            if(!TextUtils.isEmpty(name)){
                tv_userName.setText(name);
            }else {
                Intent intent = new Intent(getActivity(),LoginActivity.class);
                IntentUtils.startActivity(getActivity(),intent);
            }
            photo = (String) SharePreferenceUtils.get(getActivity(),"photo","");
            if(!TextUtils.isEmpty(photo)){
                ImageLoaderModel.instance().displayImage(photo,iv_photo);
            }
            number  = (String) SharePreferenceUtils.get(getActivity(),"loginname","");
            if(!TextUtils.isEmpty(number)){
                tv_phoneNumber.setText(number);
            }
            checkMessage();
    }

    private void initView(View view) {
        iv_photo = (CircleImageView) view.findViewById(R.id.iv_photo);
        iv_photo.setOnClickListener(this);
        tv_userName = (TextView) view.findViewById(R.id.tv_userName);
        tv_phoneNumber = (TextView) view.findViewById(R.id.tv_phoneNumber);
        rl_message = (RelativeLayout) view.findViewById(R.id.rl_message);
        rl_message.setOnClickListener(this);
        rl_update = (RelativeLayout) view.findViewById(R.id.rl_update);
        rl_update.setOnClickListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                check();
            }
        });
        rl_clear_cache = (RelativeLayout) view.findViewById(R.id.rl_clear_cache);
        rl_clear_cache.setOnClickListener(this);
        rl_reset_password = (RelativeLayout) view.findViewById(R.id.rl_reset_password);
        rl_reset_password.setOnClickListener(this);
        btn_login_out = (Button) view.findViewById(R.id.btn_login_out);
        btn_login_out.setOnClickListener(this);
        view_message = view.findViewById(R.id.view_message);
    }

    private void check(){
        if(!NewWorkUtils.isConnected(getContext())){
            ToastUtils.showShort(getActivity(),"当前网络不好");
            return;
        }
        CheckVersionModel model = new CheckVersionModel();
        model.check(CommonUtils.getVersionCode(getActivity()));
        // model.check("1");
        model.setCallBackListener(new BaseModel.CallBackListener<String>() {
            @Override
            public void success(String message)  {
                if(message!=null){
                    try {
                        JSONObject object = new JSONObject(message);
                        if(object.getInt("code")==1){
                            JSONObject object1 = object.getJSONObject("data");
                            appUrl = object1.getString("url");
                            //remark  === 提示信息
                            Log.d("zhouzhuo","appUrl:"+appUrl);
                            showDownloadDialog(object1.getString("remark"));
                        }else {
                            ToastUtils.showShort(getActivity(),object.getString("data"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }
            @Override
            public void failed() {

            }
        });
    }



    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.rl_message :
                Intent intent = new Intent(getActivity(),MineMessageActivity.class);
                IntentUtils.startFragmentToActivity(this,intent,true,10);
                break;
            case R.id.rl_clear_cache:
                String str = ClearCacheUtils.getTotalCacheSize(getActivity());
                if("0.0B".equals(str)){
                    ToastUtils.showShort(getActivity(),"没有更多缓存");
                }else {
                    ToastUtils.showShort(getActivity(),"缓存清理完成");
                    //clearCacheDialog();
                }
                break;
            case R.id.btn_login_out:
                intent = new Intent(getActivity(),LoginActivity.class);
                IntentUtils.startFragmentToActivity(this,intent,false,0);
                SharePreferenceUtils.put(getActivity(),"id","");
                SharePreferenceUtils.put(getActivity(),"login","");
                SharePreferenceUtils.put(getActivity(),"photo","");
                SharePreferenceUtils.put(getActivity(),"name","");
                SharePreferenceUtils.put(getActivity(),"loginname","");
                ConstantsUtils.bean = null;
                getActivity().finish();
                break;
            case R.id.iv_photo:
             requestPermission(new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE}, new PermissionHandler() {
                    @Override
                    public void onGranted() {
                        ImgSelActivity.startActivity(getActivity(), MyApplication.config,0);
                    }

                    @Override
                    public void onDenied() {
                        Toast.makeText(getActivity(), R.string.permission_cancel_tips, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public boolean onNeverAsk() {
                        new AlertDialog.Builder(getActivity())
                                .setTitle(R.string.permission_dialog_title)
                                .setMessage(R.string.permission_dialog_message_camera_store)
                                .setPositiveButton(R.string.permission_dialog_positive_btn, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                        Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
                                        intent.setData(uri);
                                        startActivity(intent);
                                        dialog.dismiss();
                                    }
                                })
                                .setNegativeButton(R.string.permission_dialog_negative_btn, null)
                                .setCancelable(false)
                                .show();
                        return true;
                    }
                });
                break;
            case R.id.rl_reset_password:
                intent = new Intent(getActivity(),ResetPasswordActivity.class);
                IntentUtils.startFragmentToActivity(this,intent,false,10);
                break;
        }
    }

    public void compressFile(String path){
        final File file = new File(path);
        Luban.with(getActivity())
                .load(file)                     //传人要压缩的图片
                .setCompressListener(new OnCompressListener() { //设置回调
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI

                    }
                    @Override
                    public void onSuccess(File file2) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
                        setIcon(file2.getPath());

                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                    }
                }).launch();    //启动压缩
    }

    public void setIcon(final String path) {
        PhotoUploadModel uploadModel = new PhotoUploadModel();
        uploadModel.photoUpload(getActivity(),(String)SharePreferenceUtils.get(getActivity(),"id",""),path);
        ToastUtils.showShort(getActivity(),"图片上传中");
        uploadModel.setCallBackListener(new BaseModel.CallBackListener<String>() {
            @Override
            public void success(String str) {
                try {
                    JSONObject object = new JSONObject(str);
                    int  code = object.getInt("code");
                   if(code == 1){
                        String photo = object.getJSONObject("data").getString("photo");
                        Message message = Message.obtain();
                        message.what = 0;
                        message.obj = photo;
                        handler.sendMessage(message);
                    }else {
                       Message message = Message.obtain();
                       message.what = 1;
                       message.obj = object.getString("data");
                       handler.sendMessage(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    upLoadFailed();
                }

            }

            @Override
            public void failed() {
               upLoadFailed();
            }
        });
    }

    private void upLoadFailed(){
        Message message = Message.obtain();
        message.what = 1;
        message.obj = "图片上传失败";
        handler.sendMessage(message);
    }

    private void downloadApk(String remark) {
        Intent service = new Intent(getActivity(), DownLoadService.class);
        service.putExtra("downloadurl",appUrl);
        service.putExtra("remark",remark);
        activity.startService(service);

    }



    /**
     * 弹出下载框
     */
    private void showDownloadDialog(final String remark) {
        // 下载apk
        ((MainActivity)getActivity()).requestPermission(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}
                , new BaseActivity.PermissionHandler() {
                    @Override
                    public void onGranted() {
                        downloadApk(remark);
                    }

                    @Override
                    public void onDenied() {

                    }

                    @Override
                    public boolean onNeverAsk() {
                        return false;
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if(handler !=null){
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    public abstract class OnMultiClickListener implements View.OnClickListener{
        // 两次点击按钮之间的点击间隔不能少于1000毫秒
        private static final int MIN_CLICK_DELAY_TIME = 5000;
        private long lastClickTime;

        public abstract void onMultiClick(View v);

        @Override
        public void onClick(View v) {
            long curClickTime = System.currentTimeMillis();
            if((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
                // 超过点击间隔后再将lastClickTime重置为当前点击时间
                lastClickTime = curClickTime;
                onMultiClick(v);
            }
        }
    }

}
